<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>个人中心</title>
    <link rel="stylesheet" href="../lib/layui/css/layui.css" />
    <link rel="stylesheet" href="../css/base.css" />
    <link rel="stylesheet" href="../css/form.css" />
  </head>

  <body>
    <div class="header container">
      个人中心
      <p style="display: block">
        <a href="./rpwd.html">修改密码</a>
        <a href="./index.html">回到首页</a>
      </p>
    </div>
    <form>
      <label>
        用户名： <input type="text" class="username" name="username" disabled />
      </label>
      <label> 年龄： <input type="text" name="age" class="age" /> </label>
      <label>
        性别：
        <select class="gender" name="gender">
          <option value="">请选择</option>
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </label>
      <label>
        昵称： <input type="text" name="nickname" class="nickname" />
      </label>
      <button type="submit">确认修改</button>
    </form>
    <script src="../lib/jquery.js"></script>
    <script src="../lib/axios.js"></script>
    <script>
      $(function () {
        var id = sessionStorage.getItem("id");
        var token = sessionStorage.getItem("token");

        axios
          .get(`http://localhost:9000/users/info?id=${id}`, {
            headers: {
              authorization: token,
            },
          })
          .then(res => {
            if (res.data.code === 1) {
              $(".username").val(res.data.user.username);
              $(".age").val(res.data.user.age);
              $(".gender").val(res.data.user.gender);
              $(".nickname").val(res.data.user.nickname);
            }
          });
        $("form").on("submit", function (event) {
          event.preventDefault();
          var username = $('input[name="username"]').val();
          var age = $('input[name="age"]').val();
          var gender = $('select[name="gender"]').val();
          var nickname = $('input[name="nickname"]').val();

          if (!username || !age || !gender || !nickname) {
            alert("请填写所有必填项");
            return;
          }

          axios
            .post(
              "http://localhost:9000/users/update",
              {
                id: id,
                age: age,
                gender: gender,
                nickname: nickname,
              },
              {
                headers: {
                  authorization: token,
                },
              }
            )
            .then(function (response) {
              if (response.data.code === 1) {
                alert(response.data.message);
                sessionStorage.setItem("nickname", nickname);
              } else {
                alert(response.data.message);
              }
            });
        });
      });
    </script>
  </body>
</html>
